﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web.Mvc;

namespace CodeContrib.Web.Mvc
{
	// http://msmvps.com/blogs/luisabreu/archive/2008/07/31/the-mvc-framework-the-tempdata-property.aspx
	[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, Inherited = true, AllowMultiple = true)]
	public class PersistTempDataAttribute : ActionFilterAttribute
	{
		private readonly IEnumerable<string> _keys;

		public PersistTempDataAttribute(params string[] keys)
		{
			_keys = keys;
		}

		public override void OnActionExecuted(ActionExecutedContext filterContext)
		{
			IDictionary<string, object> tempData = filterContext.Controller.TempData;

			IEnumerable<string> keys = tempData.Keys;

			if (_keys != null
			    && _keys.Any())
			{
				keys = keys.Where(x => _keys.Contains(x));
			}

			// Only items that have been "changed" (or "touched") will be saved.
			keys.ForEach(x => filterContext.Controller.TempData[x] = tempData[x]);
		}
	}
}